package com.pactera.miyuangroup.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.pactera.miyuangroup.common.Constants;
import com.pactera.miyuangroup.common.RedisOperation;
import com.pactera.miyuangroup.db.entity.Menu;
import com.pactera.miyuangroup.db.entity.OrganizationStructure;
import com.pactera.miyuangroup.db.mapper.OrganizationStructureMapper;
import com.pactera.miyuangroup.service.MiyuanDataService;
import com.pactera.miyuangroup.service.OrganizationStructureService;
import com.pactera.miyuangroup.vo.convertor.OrganizationConvert;
import com.pactera.miyuangroup.vo.response.miyuan.MiYuanModel;
import com.pactera.miyuangroup.vo.response.miyuan.MiYuanPage;
import com.pactera.miyuangroup.vo.response.miyuan.Organization;
import com.pactera.miyuangroup.vo.response.web.OrganizationRes;
import com.pactera.miyuangroup.vo.response.web.TreeMenuRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * <p>
 * 组织结构信息 服务实现类
 * </p>
 *
 * @author WangWu
 * @since 2018-04-13
 */
@Service
@Slf4j
public class OrganizationStructureServiceImp extends ServiceImpl<OrganizationStructureMapper, OrganizationStructure> implements OrganizationStructureService {
    @Autowired
    private RedisOperation redis;
    @Autowired
    private MiyuanDataService miyuanDataService;
    @Autowired
    private OrganizationConvert organizationConvert;

    /**
     * 米源机构信息同步
     *
     * @return
     */
    @Override
    public boolean syncMiyuanOrgInfo() {
        //开始更新
        try {
            miYuanOrgInfo();
        } catch (Exception e) {
            log.error("同步米源机构信息发生异常", e);
            return false;
        }
        return true;
    }

    /**
     * 机构树
     *
     * @return
     */
    @Override
    public List<OrganizationRes> getTreeOrgList() {
        EntityWrapper<OrganizationStructure> ew = new EntityWrapper<>();
        ew.eq("pid", "ROOT");
        List<OrganizationStructure> ms = selectList(null);
        List<OrganizationStructure> mso = selectList(ew);
        List<OrganizationRes> lists = new ArrayList<OrganizationRes>();
        for (OrganizationStructure m : mso) {
            OrganizationRes childArray = null;
            childArray = organizationConvert.convert2Organization(m);
            childArray.setChildren(orgChild(ms, m.getId()));
            lists.add(childArray);
        }
        return lists;
    }


    /**
     * 递归 机构树
     *
     * @param m
     * @param id
     * @return
     */
    private List<OrganizationRes> orgChild(List<OrganizationStructure> m, String id) {
        List<OrganizationRes> lists = new ArrayList<OrganizationRes>();
        lists = m.stream().filter(o -> id.equals(o.getPid())).map(c -> {
            OrganizationRes childArray = null;
            childArray = organizationConvert.convert2Organization(c);
            childArray.setChildren(orgChild(m, c.getId()));
            return childArray;
        }).collect(Collectors.toList());
        if (lists.size() <= 0) {
            lists = null;
        }
        return lists;

    }

    /**
     * 同步米源数据
     */
    private void miYuanOrgInfo() {
        int n = 1;
        MiYuanModel<MiYuanPage<Organization>> orgInfos = miyuanDataService.getOrganizationInfo(n, 100);
        while (true) {
            n++;
            //是否成功
            //失败，跳出，继续下一页
            if (!orgInfos.isSuccess()) {
                continue;
            }

            //验证是否有数据，没有数据 跳出 继续下一页
            if (orgInfos.getData() == null || orgInfos.getData().getRecords() == null && orgInfos.getData().getRecords().size() <= 0) {
                continue;
            }

            //更新机构集合
            List<OrganizationStructure> upInfos = new ArrayList<>();
            //新增机构集合
            List<OrganizationStructure> instInfos = new ArrayList<>();

            //循环数据入库
            for (Organization orgInfo : orgInfos.getData().getRecords()) {
                //查询数据库是否存在数据
                EntityWrapper<OrganizationStructure> ew = new EntityWrapper<>();
                ew.eq("original_id", orgInfo.getId());
                OrganizationStructure info = selectOne(ew);
                if (null != info) {
                    //存在，更新数据
                    info.setOriginalId(orgInfo.getId());
                    info.setName(orgInfo.getName());
                    info.setPid(orgInfo.getPid());
                    upInfos.add(info);
                } else {
                    //不存在，新增数据
                    info = new OrganizationStructure();
                    info.setOriginalId(orgInfo.getId());
                    info.setName(orgInfo.getName());
                    info.setPid(orgInfo.getPid());
                    instInfos.add(info);
                }
            }

            //更新
            if (upInfos.size() > 0) {
                updateBatchById(upInfos, upInfos.size());
            }
            //新增
            if (instInfos.size() > 0) {
                insertBatch(instInfos, instInfos.size());
            }

            //最后一页，退出
            if (orgInfos.getData().isLast()) {
                break;
            }
            orgInfos = miyuanDataService.getOrganizationInfo(n, 100);
        }

        //整理不能之间层级关系
        List<OrganizationStructure> orgAll = selectList(null);
        for (OrganizationStructure org : orgAll) {

            //查询pid对应主键ID
            EntityWrapper<OrganizationStructure> ew = new EntityWrapper<>();
            ew.eq("original_id", org.getPid());
            OrganizationStructure info = selectOne(ew);
            //更新PID
            if (null != info) {
                org.setPid(info.getId());
                updateById(org);
            }
        }
    }
}
